<?php

namespace app\admin\controller;

use app\admin\library\Auth;
use app\admin\model\Area;
use app\common\controller\Backend;
use app\exceptions\ApiException;
use app\job\AddScenic;
use ba\Exception;
use ba\ScenicApi;
use think\facade\Queue;

/**
 * 景区管理
 */
class Scenic extends Backend
{
    /**
     * Scenic模型对象
     * @var object
     * @phpstan-var \app\admin\model\Scenic
     */
    protected object $model;

    protected string|array $defaultSortField = 'weigh,desc';


    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected string|array $quickSearchField = ['id'];

    protected array $withJoinTable = ['cate'];


    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\Scenic();
        $this->request->filter('clean_xss');
    }


    public function index(): void
    {
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $this->success('', [
            'list' => $res->items(),
            'total' => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 添加
     */
    public function add(): void
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate();
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $city = (new \app\admin\model\Area())->where(['id' => $data['city']])->column('name');
                $data['city_name'] = $city[1] ?? '';
                $data['province_name'] = $city[0] ?? '';
                $data['scenic_id'] = 0;
                $result = $this->model->save($data);
                $this->model->commit();
            } catch (\Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }


    public function getList()
    {
        $data = $this->request->post();
        $scenic_name = $data['scenic_name'] ?? '';
        $page = $data['page'] ?? 1;
        $pageSize = $data['pageSize'] ?? 10;
        if (!$scenic_name) {
            $this->error('请填写关键词');
        }
        $list = (new ScenicApi())->searchScenic($scenic_name, $page, $pageSize);
        if (!$list) {
            $this->error('服务器错误');
        }
        foreach ($list['result'] as &$value) {
            unset($value['dis_list']);
        }
        $this->success('', [
            'list' => $list['result'],
            'total' => $list['totalCount'],
            'remark' => get_route_remark(),
        ]);
    }


    public function addScenic()
    {
        $data = $this->request->post();
        if (!$data) {
            $this->error('请选择景点');
        }
        Queue::push(\app\job\AddScenic::class, $data,AddScenic::$queue);
        $this->success('脚本正在执行，请稍后刷新列表');
    }


    /**
     * 编辑
     * @throws Throwable
     */
    public function edit(): void
    {
        $pk  = $this->model->getPk();
        $id  = $this->request->param($pk);
        $row = $this->model->find($id);

        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate && ($data['status'] == 1 &&  !isset($data['name']))) {
                    $res = $row->toArray();
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate();
                        $data[$pk] = $row[$pk];
                        $validate->scene('edit')->check($res);
                    }
                }

               $city = (new \app\admin\model\Area())->where(['id' => $data['city']])->column('name');
               $data['city_name'] = $city[1] ?? '';
               $data['province_name'] = $city[0] ?? '';

                $result = $row->save($data);
                $this->model->commit();
            } catch (\Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }

        $city[0] = (new Area())->where(['name' => $row['province_name']])->value('id');
        $city[1]=  (new Area())->where(['name' => $row['city_name'],'pid' => $city[0]])->value('id');
        $row['city'] = $city;
        $this->success('', [
            'row' => $row
        ]);
    }


    /**
     * 冻结（锁满）
     */
    public function freeze(): void
    {
        $data = $this->request->post();
        if(!$data) $this->error('请选择锁满项');
        $result = $this->model->where(['id' => $data['ids']])->update(['is_lock' => 1, 'lock_reason' => $data['reason']]);
        if ($result) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    /**
     * 解冻（解锁）
     */
    public function unhitch(): void
    {
        $data = $this->request->post();
        if(!$data) $this->error('请选择解锁项');
        $result = $this->model->where(['id' => $data['ids']])->update(['is_lock' => 0, 'lock_reason' => null]);
        if ($result) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    /**
     * 锁满
     * @throws Throwable
     */
    public function lock(): void
    {
        $pk  = $this->model->getPk();
        $id  = $this->request->param($pk);
        $row = $this->model->find($id);

        if (!$row) {
            $this->error(__('Record not found'));
        }
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);

            if($data['is_lock'] == 1 && !$data['lock_reason']){
                $this->error('请填写锁满原因');
            }
            if($data['is_lock'] == 0){
                $data['lock_reason'] = '';
            }

            $result = false;
            $this->model->startTrans();
            try {

                $result = $row->save($data);
                $this->model->commit();
            } catch (\Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }
    }





    public function batch(): void
    {

            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
            $result = false;
            $this->model->startTrans();
        try {
            $vip_card_ids = $data['vip_card_ids'] ?? '';
            $scenic_ids = $data['scenic_ids'] ?? '';
            if (!$vip_card_ids) $this->error('请选择会员卡');
            if (!$scenic_ids) $this->error('请选择数据');
            $vip_card = implode(',', $vip_card_ids);
            $result = $this->model->where(['id' => $scenic_ids])->update(['vip_card_ids' => $vip_card]);
            $this->model->commit();
        } catch (\Throwable $e) {
            $this->model->rollback();
            $this->error($e->getMessage());
        }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
    }





    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */
}
